package com.zggk.iroad.diease.dieaselist;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.bigkoo.pickerview.TimePickerView;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zggk.iroad.R;
import com.zggk.iroad.adapter.listview.CommonAdapter;
import com.zggk.iroad.adapter.listview.ViewHolder;
import com.zggk.iroad.db.DieaseInfo;
import com.zggk.iroad.db.EntityManager;
import com.zggk.iroad.diease.dieaseadd.DieaseAddActivity;
import com.zggk.iroad.diease.dieasedb.DieaseDbActivity;
import com.zggk.iroad.diease.dieasemx.DieaseMxActivity;
import com.zggk.iroad.greendao.DieaseInfoDao;
import com.zggk.iroad.mvp.MVPBaseActivity;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import static com.blankj.utilcode.util.SizeUtils.dp2px;

/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class DieaseListActivity extends MVPBaseActivity<DieaseListContract.View, DieaseListPresenter> implements DieaseListContract.View {


    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.cancle_button)
    TextView cancleButton;
    @Bind(R.id.month_txt)
    TextView monthTxt;
    @Bind(R.id.month_layout)
    RelativeLayout monthLayout;
    @Bind(R.id.log_rv)
    SwipeMenuListView waihandleRv;
    @Bind(R.id.sm_lay)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.up_te)
    TextView upTe;
    @Bind(R.id.add_te)
    TextView addTe;
    @Bind(R.id.add_lay)
    LinearLayout addLay;

    private int PAGEINDEX;
    private DieaseInfoDao dieaseInfoDa;
    private List<DieaseInfo> Datas = new ArrayList<>();
    private CommonAdapter<DieaseInfo> adapter;

    @Override
    public void onRequestError(String msg) {

    }

    @Override
    protected int getLayout() {
        return R.layout.act_diease_list;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        initAdapter();
        initView();
        initData();
    }

    private void initAdapter() {
        waihandleRv.setMenuCreator(creator);
        adapter = new CommonAdapter<DieaseInfo>(DieaseListActivity.this,
                R.layout.item_diease, Datas) {
            @Override
            protected void convert(final ViewHolder holder, DieaseInfo zCDBean, final int position) {
                holder.setImageUrl( R.id.dieast_img, zCDBean.getTPDZ());
                holder.setText(R.id.disease_lxbm, zCDBean.getLXMC());
                holder.setText(R.id.disease_bhmc, zCDBean.getBHMCMC());
                holder.setText(R.id.disease_sj, zCDBean.getXCSJ());
                if (zCDBean.getISDB().equals("1")) {
                    holder.setText(R.id.disease_zt, "未上传");
                    holder.setTextColor(R.id.disease_zt, Color.parseColor("#39a9ff"));
                } else if (zCDBean.getISDB().equals("0")) {
                    holder.setText(R.id.disease_zt, "已上传");
                    holder.setTextColor(R.id.disease_zt, Color.parseColor("#2cb303"));
                }
            }
        };
        waihandleRv.setAdapter(adapter);
        waihandleRv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (refreshLayout.isRefreshing() || refreshLayout.isLoading()) {
                    ToastUtils.showShort("等待数据加载完成再进行操作");
                } else {
                    if (Datas.get(position).getISDB().equals("1")) {//本地
                        Intent intent = new Intent(DieaseListActivity.this, DieaseDbActivity.class);
                        intent.putExtra("RZID", Datas.get(position).getId());
                        startActivityForResult(intent, 1);
                    } else {//网络
                        Intent intent = new Intent(DieaseListActivity.this, DieaseMxActivity.class);
                        intent.putExtra("RZID", Datas.get(position).getBHID());
                        startActivity(intent);
                    }
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 2) {
            if (requestCode == 1) {
                refreshLayout.autoRefresh();
            }
        }
    }

    private void initData() {
        refreshLayout.autoRefresh();
    }

    private void initView() {
        titleText.setText("病害采集");
        dieaseInfoDa = EntityManager.getInstance().getDieaseInfoDao();
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if (NetworkUtils.isAvailableByPing()) {//有网
                    PAGEINDEX = 1;
                    mPresenter.testinfo(monthTxt.getText().toString(), PAGEINDEX);
                } else {
                    Datas.clear();
                    Datas.addAll(dieaseInfoDa.loadAll());
                    adapter.notifyDataSetChanged();
                    if (refreshLayout.isRefreshing()) {
                        refreshLayout.finishRefresh();
                    }
                }
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (NetworkUtils.isAvailableByPing()) {//有网
                    PAGEINDEX++;
                    mPresenter.testinfo(monthTxt.getText().toString(), PAGEINDEX);
                } else {
                    Datas.clear();
                    Datas.addAll(dieaseInfoDa.loadAll());
                    if (refreshLayout.isLoading()) {
                        refreshLayout.finishLoadmore();
                    }
                }

            }
        });
        waihandleRv.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:

                        break;
                    case 1:
                        mPresenter.deleteById(Datas.get(position).getBHID());
                        break;
                }
                return true;
            }
        });
        monthTxt.setText(new SimpleDateFormat("yyyy年MM月dd日").format(Calendar.getInstance().getTime()));
    }

    @OnClick({R.id.back, R.id.up_te, R.id.month_txt, R.id.add_lay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.month_txt:
                TimePickerView ksTimes = new TimePickerView.Builder(DieaseListActivity.this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        monthTxt.setText(new SimpleDateFormat("yyyy年MM月dd日").format(date));
                    }
                }).setType(new boolean[]{true, true, true, false, false, false})
                        .build();
                ksTimes.setDate(Calendar.getInstance());
                ksTimes.show();
                break;
            case R.id.up_te:
                break;
            case R.id.add_lay:
                Intent intent = new Intent(DieaseListActivity.this, DieaseAddActivity.class);
                startActivityForResult(intent, 1);
                break;
        }
    }

    @Override
    public void getData(DiseaseListbean videoVos2) {
        if (refreshLayout.isLoadmoreFinished()) {
            refreshLayout.setLoadmoreFinished(false);
        }
        if (videoVos2.getBHLIST() != null && videoVos2.getBHLIST().size() > 0) {
            if (PAGEINDEX == 1) {
                Datas.clear();
                Datas.addAll(dieaseInfoDa.loadAll());
            }
            for (int i = 0; i < videoVos2.getBHLIST().size(); i++) {
                DieaseInfo logInfo = new DieaseInfo();
                logInfo.setTPDZ(videoVos2.getBHLIST().get(i).getTPDZ());//图片
                logInfo.setLXMC(videoVos2.getBHLIST().get(i).getLXBM() + " " + videoVos2.getBHLIST().get(i).getBHMC());//路线
                logInfo.setBHMCMC(videoVos2.getBHLIST().get(i).getBHMC());//病害名称
                logInfo.setXCSJ(videoVos2.getBHLIST().get(i).getDCSJ());//时间
                logInfo.setBHID(videoVos2.getBHLIST().get(i).getBHID());//病害ID
                logInfo.setISDB("0");//状态
                Datas.add(logInfo);
            }
            adapter.notifyDataSetChanged();
            if (videoVos2.getBHLIST().size() < 20) {
                refreshLayout.setLoadmoreFinished(true);
            }
        } else {
            refreshLayout.setLoadmoreFinished(true);
        }
        if (refreshLayout.isRefreshing()) {
            refreshLayout.finishRefresh();
        }
        if (refreshLayout.isLoading()) {
            refreshLayout.finishLoadmore();
        }
    }

    @Override
    public void deleteByIds() {
        refreshLayout.autoRefresh();
    }

    SwipeMenuCreator creator = new SwipeMenuCreator() {

        @Override
        public void create(SwipeMenu menu) {
            SwipeMenuItem deleteItem = new SwipeMenuItem(getApplicationContext());
            deleteItem.setBackground(R.color.pf_ypf_text_color);
            deleteItem.setWidth(dp2px(90));
            deleteItem.setTitle("撤销");
            deleteItem.setTitleSize(18);
            deleteItem.setTitleColor(Color.WHITE);
            menu.addMenuItem(deleteItem);
            SwipeMenuItem deleteItem2 = new SwipeMenuItem(getApplicationContext());
            deleteItem2.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
            deleteItem2.setWidth(dp2px(90));
            deleteItem2.setTitle("删除");
            deleteItem2.setTitleSize(18);
            deleteItem2.setTitleColor(Color.WHITE);
            menu.addMenuItem(deleteItem2);
        }
    };
}
